package com.ctvit.sms.platform.service;

import com.ctvit.common.DateTimeUtil;
import com.ctvit.common.StringTrans;
import com.ctvit.framework.dao.Condition;
import com.ctvit.framework.dao.OrderPart;
import com.ctvit.framework.service.BaseService;
import com.ctvit.sms.platform.domain.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.BadSqlGrammarException;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by LoreYun on 2016/3/10.
 */
public class CustomMsgService extends BaseService {
	private static Logger logger = Logger.getLogger(CustomMsgService.class);

	private static int TEXT_SHOW_COUNT = 3;                //文本消息-接收人员默认显示个数
	private static int MEET_SHOW_COUNT = 3;                //会议通知-接收人员默认显示个数

	//===========list============      start
	public HashMap getTextListTDataByUserId(String userId) {
		logger.debug("getTextListTDataByUserId: userId:" + userId);

		HashMap result;
		List<HashMap> rows;

		if (StringUtils.isEmpty(userId)) {
			logger.error("[ERRORINFO]getTextListTDataByUserId 传入的用户ID为空");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();


		List<CmsgText> textList = getTextListByUserId(userId, "createTimestamp", OrderPart.DESC);
		if (textList == null || textList.size() < 0) {
			logger.debug("getTextListTDataByUserId: 该人员没有发送文本消息的记录");
		} else {
			for (CmsgText text : textList) {
				HashMap row = new HashMap();
				String info, content, retrievePerson = "", retrievePersonAll = "", HTMLID;
				info = "创建时间:<br>" + DateTimeUtil.formatDate(text.getCreateTimestamp());
				info += "<br>" + DateTimeUtil.formatTime(text.getCreateTimestamp());

				content = text.getContent();
				content = StringTrans.replaceAllCRLF(content, "<br>");
				//给<a>查看全部</a>时候用的
				HTMLID = "text_" + text.getMessagePk();

				List<CmsgRetrieveWithNaGp> cmsgRetrieveList = getRetrieveWithNaGp(text.getMessagePk(), 0);    //文本消息的type为 0
				for (int i = 0; i < cmsgRetrieveList.size(); i++) {
					CmsgRetrieveWithNaGp retMember = cmsgRetrieveList.get(i);
					if (i < TEXT_SHOW_COUNT) {      //在接收人列显示几个人
						retrievePerson += retMember.getZPerna() + "、";
					}

					retrievePersonAll += retMember.getZPerna();
					retrievePersonAll += "(" + retMember.getGetUsersId() + ")、";
				}
				//table上显示的接收人列
				if (retrievePersonAll.equals("")) {       //按理说不应该没有人  但是怕下面删除最后一个、的时候出错
					retrievePersonAll = "无";
				} else {
					retrievePerson = retrievePerson.substring(0, retrievePerson.length() - 1);     //删除最后一个“、”
					if (cmsgRetrieveList.size() > TEXT_SHOW_COUNT) {        //如果大于设定的人数 显示小数点
						retrievePerson += "...";
					}
				}
				retrievePerson += "<br><a href=\"javascript:void(0)\" onclick=\"showAll('" + HTMLID + "')\">查看全部</a>";
				//点击查看全部之后显示的
				if (retrievePersonAll.equals("")) {       //按理说不应该没有人  但是怕下面删除最后一个、的时候出错
					retrievePersonAll = "无";
				} else {
					retrievePersonAll = retrievePersonAll.substring(0, retrievePersonAll.length() - 1);     //删除最后一个“、”
				}
				retrievePersonAll = "<div id='" + HTMLID + "'>" + retrievePersonAll + "</div>";

				row.put("info", info);
				row.put("content", content);
				row.put("retrievePerson", retrievePerson);
				row.put("retrievePersonAll", retrievePersonAll);
				rows.add(row);
			}
		}

		result.put("total", rows.size());
		result.put("rows", rows);
		return result;
	}

	public HashMap getMeetingListTDataByUserId(String userId) {
		logger.debug("getMeetingListTDataByUserId: userId:" + userId);

		HashMap result;
		List<HashMap> rows;

		if (StringUtils.isEmpty(userId)) {
			logger.error("[ERRORINFO]getMeetingListTDataByUserId 传入的用户ID为空");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();


		List<CmsgMeeting> meetingList = getMeetingListByUserId(userId, "createTimestamp", OrderPart.DESC);
		if (meetingList == null || meetingList.size() < 0) {
			logger.debug("getMeetingListTDataByUserId: 该人员没有会议通知的记录");
		} else {
			for (CmsgMeeting meeting : meetingList) {
				HashMap row = new HashMap();
				StringBuffer info, content, attach,
						retrievePerson = new StringBuffer(), retrievePersonAll = new StringBuffer();
				String HTMLID;
				List<Attach> attachList;

				info = new StringBuffer("创建时间:<br>" + DateTimeUtil.formatDate(meeting.getCreateTimestamp()));
				info.append("<br>" + DateTimeUtil.formatTime(meeting.getCreateTimestamp()));

				content = new StringBuffer("【会议通知】" + meeting.getTitle());
				content.append("<br>【会议日期】" + DateTimeUtil.formatDate(meeting.getDate()));
				content.append("<br>【会议时间】" + meeting.getStartTime());
				content.append("<br>【会议地点】" + meeting.getAddress());
				content.append("<br>【联 系 人】" + meeting.getContactPerson());
				content.append("<br>【联系电话】" + meeting.getContact());
//				content.append("<br>【会议描述】" + StringTrans.replaceAllCRLF(meeting.getDesc(), "<br>"));      //TODO 先不管回车
				content.append("<br>【会议描述】" + meeting.getDesc());

				//附件
				attach = new StringBuffer("<br>【 附  件 】");

				attachList = getAttachList("t_cmsg_meeting", meeting.getMessagePk().toString(), true);
				if (attachList.isEmpty() == true) {
					attach.append(" - 无附件 - ");
				} else {
					String url = "/messageCenter/attached/newsite/" + meeting.getMessagePk() + "/";
					attach.append("<div style=\"vertical-align: top;display: inline-block;_display:inline;*display:inline;zoom:1;\">");

					for (int i = 0; i < attachList.size(); i++) {
						Attach oneAttach = attachList.get(i);
						int orderIndex = i + 1;

						attach.append("<a href='" + url + oneAttach.getFileName() + "' target='_blank'>");
						attach.append(orderIndex + "." + oneAttach.getFileName());
						attach.append("</a><br>");
					}
					attach.append("</div>");
				}
				content.append(attach);

				//给<a>查看全部</a>时候用的
				HTMLID = "meeting_" + meeting.getMessagePk();

				//在表格中显示部分接收人
				List<CmsgRetrieveWithNaGp> cmsgRetrieveList = getRetrieveWithNaGp(meeting.getMessagePk(), 1);    //会议通知的type为 1
				for (int i = 0; i < cmsgRetrieveList.size(); i++) {
					CmsgRetrieveWithNaGp retMember = cmsgRetrieveList.get(i);
					if (i < MEET_SHOW_COUNT) {      //在接收人列显示几个人
						retrievePerson.append(retMember.getZPerna() + "、");
					}
					retrievePersonAll.append(retMember.getZPerna());
					retrievePersonAll.append("(" + retMember.getGetUsersId() + ")、");
				}
				//table上显示的接收人列
				if (retrievePerson.equals("")) {       //按理说不应该没有人  但是怕下面删除最后一个、的时候出错
					retrievePersonAll.append(" - 无 - ");
				} else {
					retrievePerson.deleteCharAt(retrievePerson.length() - 1);          //删除最后一个“、”

					if (cmsgRetrieveList.size() > MEET_SHOW_COUNT) {        //如果大于设定的人数 显示小数点
						retrievePerson.append("...");
					}
				}
				retrievePerson.append("<br><a href=\"javascript:void(0)\" onclick=\"showAll('" + HTMLID + "')\">查看全部</a>");
				//点击查看全部之后显示的
				if (retrievePersonAll.equals("")) {       //按理说不应该没有人  但是怕下面删除最后一个、的时候出错
					retrievePersonAll.append("无");
				} else {
					retrievePersonAll.deleteCharAt(retrievePersonAll.length() - 1);         //删除最后一个“、”
				}
				retrievePersonAll.insert(0, "<div id='" + HTMLID + "'>");
				retrievePersonAll.append("</div>");

				row.put("info", info.toString());
				row.put("content", content.toString());
				row.put("retrievePerson", retrievePerson.toString());
				row.put("retrievePersonAll", retrievePersonAll.toString());
				rows.add(row);
			}
		}

		result.put("total", rows.size());
		result.put("rows", rows);
		return result;
	}

	/**
	 * 根据meeting或者text表的主键 搜索该通知的接收人
	 * pk+type的原因是 pk是meeting或者text表的主键   type区分是text - 0还是 meeting - 1表
	 *
	 * @param messagePk t_cmsg_meeting 或者  t_cmsg_text 的主键
	 * @param type      0   文本消息
	 *                  1  会议
	 * @return
	 */
	public List<CmsgRetrieveWithNaGp> getRetrieveWithNaGp(Long messagePk, Integer type) {
		logger.debug("getRetrieveWithNaGp:messagePk:" + messagePk + ",type:" + type);
		List<CmsgRetrieveWithNaGp> result;
		if (messagePk == null || messagePk == 0) {
			result = new ArrayList<CmsgRetrieveWithNaGp>();
			return result;
		} else if (type == null) {
			result = new ArrayList<CmsgRetrieveWithNaGp>();
			return result;
		}

		HashMap conditionMap = new HashMap();
		conditionMap.put("messagePk", messagePk);
		conditionMap.put("type", type);
		return genericDao.queryBySqlID("platform.cmsgretrieve.CmsgRetrieveWithNaGp", conditionMap);
	}

	/**
	 * 根据  t_cmsg_retrieve 表中 的外键：messagePK和类型(文本消息或者会议消息)找到该接收人
	 *
	 * @param messagePk t_cmsg_meeting 或者  t_cmsg_text 的主键
	 * @param type      0   文本消息
	 *                  1  会议
	 * @return
	 */
	public List<CmsgRetrieve> getRetrieveList(Long messagePk, Integer type) {
		logger.debug("getRetrieveList:messagePk:" + messagePk + ",type:" + type);
		List<CmsgRetrieve> result;
		if (messagePk == null || messagePk == 0) {
			result = new ArrayList<CmsgRetrieve>();
			return result;
		} else if (type == null || type == 0) {
			result = new ArrayList<CmsgRetrieve>();
			return result;
		}

		Condition condition = new Condition();
		condition.add("messagePk", messagePk);
		condition.add("type", type);
		result = genericDao.getByCondition(CmsgRetrieve.class, condition, null);

		return result;
	}

	/**
	 * 获取该用户所创建的文本消息
	 *
	 * @param userId
	 * @param order
	 * @param orderType
	 * @return
	 */
	public List<CmsgText> getTextListByUserId(String userId, String order, String orderType) {
		logger.debug("getTextListByUserId:userId:" + userId + ",order:" + order + ",orderType:" + orderType);

		Condition condition = new Condition();
		condition.add("putUserid", userId);

		OrderPart orderPart = new OrderPart();
		if (StringUtils.isNotEmpty(order)) {
			if (orderType.equals(OrderPart.ASC)) {
				orderPart.add(order, OrderPart.ASC);
			} else {
				orderPart.add(order, OrderPart.DESC);
			}
		}
		return genericDao.getByCondition(CmsgText.class, condition, orderPart);
	}

	/**
	 * 获取该用户所创建的会议通知
	 *
	 * @param userId
	 * @param order
	 * @param orderType
	 * @return
	 */
	public List<CmsgMeeting> getMeetingListByUserId(String userId, String order, String orderType) {
		logger.debug("getMeetingListByUserId:userId:" + userId + ",order:" + order + ",orderType:" + orderType);

		Condition condition = new Condition();
		condition.add("putUserid", userId);

		OrderPart orderPart = new OrderPart();
		if (StringUtils.isNotEmpty(order)) {
			if (orderType.equals(OrderPart.ASC)) {
				orderPart.add(order, OrderPart.ASC);
			} else {
				orderPart.add(order, OrderPart.DESC);
			}
		}
		return genericDao.getByCondition(CmsgMeeting.class, condition, orderPart);
	}
	//===========list============      end

	/**
	 * @param objectTable
	 * @param objectKey
	 * @param attachNo
	 * @return -1没找到对应记录
	 */
	public int doDelAttach(String objectTable, String objectKey, Long attachNo) {
		logger.debug("insertAttach:objectTable:" + objectTable + ",objectKey:" + objectKey + ",attachNo:" + attachNo);

		if (StringUtils.isEmpty(objectTable)) {
			logger.error("[ERRORINFO]doDelAttach: objectTable为空");
			return 0;
		} else if (StringUtils.isEmpty(objectKey)) {
			logger.error("[ERRORINFO]doDelAttach: objectKey为空");
			return 0;
		} else if (attachNo <= 0) {
			logger.error("[ERRORINFO]doDelAttach: attachNo为空");
			return 0;
		}

		Attach attach = new Attach();
		attach.setDelFlag("1");

		Condition condition = new Condition();
		condition.add("objectTable", objectTable.toLowerCase());
		condition.add("objectKey", objectKey.toLowerCase());
		condition.add("attachNo", attachNo);
		int effectCount = genericDao.updateByCondition(attach, new String[]{"delFlag"}, condition);
		if (effectCount == 0) {
			//没找到对应记录
			return -1;
		}

		return 1;
	}

	/**
	 * 插入附件记录  t_attach
	 *
	 * @param fileName
	 * @param fileExtend
	 * @param objectTable
	 * @param objectKey
	 * @param attachNo
	 * @return
	 */
	public Attach insertAttach(String fileName, String fileExtend, String objectTable, String objectKey, Long attachNo) {
		logger.debug("insertAttach:fileName:" + fileName + ",fileExtend:" + fileExtend
				+ ",objectTable:" + objectTable + ",objectKey:" + objectKey + ",attachNo:" + attachNo);

		Long pk;
		Attach attach = new Attach();
		attach.setFileName(fileName);
		attach.setFileExtend(fileExtend.toLowerCase());
		attach.setObjectKey(objectKey);
		attach.setObjectTable(objectTable.toLowerCase());
		attach.setAttachNo(attachNo);

		attach.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
		attach.setDelFlag(null);

		pk = genericDao.insert(attach);
		attach.setAttachPk(pk);
		return attach;
	}

	/**
	 * 获取附件表中对应table 和 key的最大的attachNo
	 *
	 * @param objectTable
	 * @param objectKey
	 * @return
	 */
	public int getLastAttachNo(String objectTable, String objectKey) {
		logger.debug("getLastAttachNo:objectTable:" + objectTable + ",objectKey:" + objectKey);

		Condition condition;
		OrderPart order;
		Attach lastAttach;

		condition = new Condition();
		condition.add("objectTable", objectTable);
		condition.add("objectKey", objectKey);

		order = new OrderPart();
		order.add("attachNo", OrderPart.DESC);

		List<Attach> result = genericDao.getPagedByCondition(Attach.class, condition, order, 0, 1);
		if (result.isEmpty()) {
			return 0;
		} else {
			lastAttach = result.get(0);
			return lastAttach.getAttachNo().intValue();
		}
	}

	/**
	 * 根据table 和 key 找到对应的附件
	 *
	 * @param objectTable
	 * @param objectKey
	 * @param isAttachNoASC
	 * @return
	 */
	public List<Attach> getAttachList(String objectTable, String objectKey, boolean isAttachNoASC) {
		logger.debug("getAttachList:objectTable:" + objectTable + ",objectKey:" + objectKey);

		Condition condition = new Condition();
		OrderPart order = new OrderPart();

		condition.add("objectTable", objectTable);
		condition.add("objectKey", objectKey);
		condition.add("", "f_del_flag IS NULL", "", true);

		if (isAttachNoASC == true) {
			order.add("attachNo", OrderPart.ASC);
		} else {
			order.add("attachNo", OrderPart.DESC);
		}
		return genericDao.getByCondition(Attach.class, condition, order);
	}

	/**
	 * 获取  会议通知主表
	 *
	 * @param pk
	 * @return
	 */
	public CmsgMeeting getCmsgMeeting(Long pk) {
		logger.debug("getCmsgMeeting");

		return genericDao.getById(CmsgMeeting.class, pk);
	}

	/**
	 * 更新自定义 会议通知
	 *
	 * @param cmsgMeeting
	 * @return
	 */
	public int doUpdateCmsgMeeting(CmsgMeeting cmsgMeeting) {
		logger.debug("doUpdateCmsgMeeting");

		return genericDao.updateExclusive(cmsgMeeting,
				new String[]{"modifyTimestamp", "createTimestamp", "messagePk", "putDeptid", "putUserid"});
	}

	public int doUpdateCmsgMeetingState(Long pk, Integer state) {
		logger.debug("doUpdateCmsgMeetingState:pk:" + pk + ",state:" + state);

		CmsgMeeting cmsgMeeting = new CmsgMeeting();
		cmsgMeeting.setMessagePk(pk);
		cmsgMeeting.setState(state);

		return genericDao.update(cmsgMeeting, new String[]{"state"});
	}
	/**
	 * 将要发送的文本消息插入数据库
	 *
	 * @param userID        //创建人ID
	 * @param title         会议主题
	 * @param date          会议日期
	 * @param startTime     会议开始时间
	 * @param endTime       会议结束时间
	 * @param address       会议地点
	 * @param participants  主要参与人
	 * @param contactPerson 会议联系人
	 * @param contact       会议联系方式
	 * @param desc          会议描述
	 * @return
	 */
	public CmsgMeeting insertCmsgMeeting(String userID, String title, Date date,
	                                     String startTime, String endTime, String address, String participants,
	                                     String contactPerson, String contact, String desc) {
		logger.debug("CmsgMeeting:userID:" + userID + ",title:" + title + ",date:" + date
				+ ",startTime:" + startTime + ",endTime:" + endTime + ",address:" + address + ",participants:" + participants
				+ ",contactPerson:" + contactPerson + ",contact:" + contact + ",desc:" + desc);

		Long pk;
		CmsgMeeting cmsgMeeting = new CmsgMeeting();

		cmsgMeeting.setTitle(title);                                        //会议主题  差 插入之前，看看有没有需要过滤的词语
		cmsgMeeting.setDate(date);                                     //会议日期
		cmsgMeeting.setStartTime(startTime);                      //会议开始时间
		cmsgMeeting.setEndTime(endTime);                         //会议结束时间
		cmsgMeeting.setAddress(address);                          //会议地点
		cmsgMeeting.setParticipants(participants);              //主要参与人
		cmsgMeeting.setContactPerson(contactPerson);     //会议联系人
		cmsgMeeting.setContact(contact);                          //会议联系方式
		cmsgMeeting.setDesc(desc);                                //会议描述

		cmsgMeeting.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
		cmsgMeeting.setState(0);   //   0 草稿状态  1 未发出 2 已生成消息
		cmsgMeeting.setPutUserid(userID);
		cmsgMeeting.setPutDeptid(getDeptIDByUserId(userID));

		pk = genericDao.insert(cmsgMeeting);                         //差 要是数据库插入错误了怎么办？
		cmsgMeeting.setMessagePk(pk);
		return cmsgMeeting;
	}

	/**
	 * 生成文本消息的 消息
	 *
	 * @param pk t_cmsg_text的主键
	 * @return
	 */
	public boolean doGeneCmsgText(Long pk) {
		logger.debug("doGeneCmsgText:pk:" + pk);

		try {
			doUpdateCmsgTextState(pk, 1);           //将状态从0-草稿状态， 更新为1-未发出
		} catch (BadSqlGrammarException exception) {
			exception.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 生成会议消息的 消息
	 *
	 * @param pk
	 * @return
	 */
	public boolean doGeneCmsgMeeting(Long pk) {
		logger.debug("doGeneCmsgMeeting:pk:" + pk);

		try {
			doUpdateCmsgMeetingState(pk, 1);           //将状态从0-草稿状态， 更新为1-未发出
		} catch (BadSqlGrammarException exception) {
			exception.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 根据主键 获取自定义文本信息
	 *
	 * @param Pk
	 * @return
	 */
	public CmsgText getCmsgText(Long Pk) {
		logger.debug("getCmsgText");

		return genericDao.getById(CmsgText.class, Pk);
	}

	/**
	 * 更新自定义短消息
	 *
	 * @param cmsgText
	 * @return
	 */
	public int doUpdateCmsgText(CmsgText cmsgText) {
		logger.debug("doUpdateCmsgText");

		return genericDao.updateExclusive(cmsgText,
				new String[]{"modifyTimestamp", "createTimestamp", "messagePk", "putDeptid", "putUserid"});
	}

	public int doUpdateCmsgTextState(Long pk, Integer state) {
		logger.debug("doUpdateCmsgTextState:pk:" + pk + ",state:" + state);

		CmsgText cmsgText = new CmsgText();
		cmsgText.setMessagePk(pk);
		cmsgText.setState(state);

		return genericDao.update(cmsgText, new String[]{"state"});
	}

	/**
	 * 将要发送的文本消息插入数据库
	 *
	 * @param msgContent
	 * @param userID
	 * @return
	 */
	public CmsgText insertCmsgText(String msgContent, String userID) {
		logger.debug("insertCmsgText:msgContent:" + msgContent + ",userID:" + userID);

		Long pk;
		CmsgText cmsgText = new CmsgText();

		cmsgText.setContent(msgContent);       //TODO 插入之前，看看有没有需要过滤的词语
//		cmsgText.setTitle(msgContent);              //不插tittle
		cmsgText.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
		cmsgText.setState(0);   //   0 草稿状态  1 未发出 2 已生成消息
		cmsgText.setPutUserid(userID);
		cmsgText.setPutDeptid(getDeptIDByUserId(userID));

		pk = genericDao.insert(cmsgText);                         //要是数据库插入错误了怎么办？
		cmsgText.setMessagePk(pk);
		return cmsgText;
	}

	/**
	 * 批量插入t_cmsg_retrieve
	 *
	 * @param retrieveList
	 * @return
	 */
	public int doBatchInsertRetrieve(List<CmsgRetrieve> retrieveList) {
		logger.debug("doBatchInsertRetrieve");

		if (retrieveList == null || retrieveList.isEmpty()) {
			logger.debug("insertRetrieveList: retrieveList为空");
			return -1;
		}
		return genericDao.batchInsert(retrieveList);
	}

	/**
	 * 删除待发送的人员
	 *
	 * @param type      0   文本消息
	 *                  1  会议
	 * @param messagePk
	 * @return
	 */
	public int doDelRetrieve(String type, Long messagePk) {
		logger.debug("doDelRetrieve");

		if (StringUtils.isEmpty(type)) {
			logger.debug("doDelRetrieve: type为空");
		} else if (messagePk <= 0) {
			logger.debug("doDelRetrieve: messagePk为空");
		}
		Condition condition = new Condition();

		condition.add("type", type);
		condition.add("messagePk", messagePk.intValue());

		return genericDao.removeByCondition(CmsgRetrieve.class, condition);
	}

	/**
	 * 插入“消息自建群组子表” 传入要插入的组号 和 用户ID
	 * 如果已经存在，则查出对应的记录 并返回
	 *
	 * @param groupID
	 * @param userID
	 * @return
	 */
	public CmsgGroupSub insertCmsgGroupSub(String groupID, String userID) {
		logger.debug("insertCmsgGroupSub: groupID:" + groupID + ",userID:" + userID);

		Long groupSubPK;
		if (groupID == null) {
			return null;
		} else if (userID == null) {
			return null;
		}
		CmsgGroupSub cmsgGroupSub = getCmsgGroupSub(groupID, userID);
		if (cmsgGroupSub == null) {
			cmsgGroupSub = new CmsgGroupSub();
			cmsgGroupSub.setGroupId(Long.parseLong(groupID));
			cmsgGroupSub.setUserId(userID);
			cmsgGroupSub.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
			groupSubPK = genericDao.insert(cmsgGroupSub);
			cmsgGroupSub.setId(groupSubPK);
		}
		return cmsgGroupSub;
	}

	/**
	 * 根据群组ID，用户ID，检查这个用户是否已经在这个组里面了
	 * 如果不存在 返回为null
	 *
	 * @param groupID
	 * @param userID
	 * @return
	 */
	public CmsgGroupSub getCmsgGroupSub(String groupID, String userID) {
		logger.debug("getCmsgGroupSub: groupID:" + groupID + ",userID:" + userID);

		Condition condition = new Condition();
		condition.add("groupId", groupID);
		condition.add("userId", userID);

		List<CmsgGroupSub> result = genericDao.getByCondition(CmsgGroupSub.class, condition, null);
		if (result.size() > 0) {
			return result.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 通过 人员工号 、 人员姓名 或者 人员所在部门名称进行搜索  来查找台内人员
	 *
	 * @param personNo
	 * @param personName
	 * @param deptName
	 * @return
	 */
	public HashMap getStaffTableData(String personNo, String personName, String deptName) {
		logger.debug("getStaffTableData: personNo:" + personNo + ",personName:" + personName + ",deptName:" + deptName);

		List<PersonWithDept> personWithDeptList = getStaffList(personNo, personName, deptName, 0, 0);
		HashMap result;
		List<HashMap> rows;
		if (personWithDeptList == null) {
			logger.error("[ERRORINFO]getStaffTableData:未找到对应的人员");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();

		for (PersonWithDept onePerson : personWithDeptList) {
			HashMap row = new HashMap();
			row.put("zPerno", onePerson.getZPerno());
			row.put("zPerna", onePerson.getZPerna());
			row.put("zMobph", onePerson.getZMobph());
			row.put("zDeptNm", onePerson.getZDeptNm());
			row.put("zDept", onePerson.getZDept());
			rows.add(row);
		}

		result.put("total", personWithDeptList.size());
		result.put("rows", rows);
		return result;
	}

	/**
	 * 根据子表的ID 删除对应记录
	 *
	 * @param cmsgGroupSubList
	 * @return
	 */
	public int doDeleteMemberFromGroup(List<CmsgGroupSub> cmsgGroupSubList) {
		logger.debug("doDeleteMemberFromGroup: cmsgGroupSubList:" + cmsgGroupSubList);

		if (cmsgGroupSubList == null) {
			logger.error("[ERRORINFO]doDeleteMemberFromGroup:传入的List 为null");
			return -1;
		} else if (cmsgGroupSubList.size() < 0) {
			logger.error("[ERRORINFO]doDeleteMemberFromGroup:传入的List 的size小于0");
			return -2;
		}
		int effectRowCount = 0;
		Condition condition = new Condition();
		for (CmsgGroupSub cmsgGroupSub : cmsgGroupSubList) {
			Long subId = cmsgGroupSub.getId();
			if (subId != 0) {
				condition.add("id", cmsgGroupSub.getId());
			} else {
				logger.debug("cmsgGroupSubList中某一个对象的PK为0");
			}
		}
		effectRowCount = genericDao.removeByCondition(CmsgGroupSub.class, condition);
		return effectRowCount;
	}

	/**
	 * 根据群组ID 获取该群组下的人员，并找到他们的姓名、电话、部门名称
	 *
	 * @param groupID
	 * @return 返回  easyui datagrid table所用的格式
	 */
	public HashMap getGpMemberTableData(String groupID) {
		logger.debug("getGpMemberTableData: groupID:" + groupID);

		List<CmsgMember> memberList = getGpMemberListByGpID(groupID);
		HashMap result;
		List<HashMap> rows;
		if (memberList == null) {
			logger.error("[ERRORINFO]getGpMemberTableData: " + groupID + "组下没有群成员");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();

		for (CmsgMember oneMember : memberList) {
			HashMap row = new HashMap();
			row.put("memberID", oneMember.getId());
			row.put("memberUserID", oneMember.getUserId());
			row.put("memberUserNm", oneMember.getZPerna());
			row.put("memberMobPh", oneMember.getZMobph());
			row.put("memberDepNm", oneMember.getZDeptNm());
			rows.add(row);
		}

		result.put("total", memberList.size());
		result.put("rows", rows);
		return result;
	}

	/**
	 * 根据组号，修改组名称
	 *
	 * @param groupID
	 * @param groupName
	 * @return
	 */
	public int doUpdateGroupName(Long groupID, String groupName) {
		logger.debug("doUpdateGroupName: groupID:" + groupID + ",groupName:" + groupName);

		int effectRowCount = 0;
		CmsgGroup cmsgGroup = new CmsgGroup();
		cmsgGroup.setGroupId(groupID);
		cmsgGroup.setGroupName(groupName);
		effectRowCount = genericDao.update(cmsgGroup, new String[]{"groupName"});
		return effectRowCount;
	}

	/**
	 * 根据传入的群组号 更新isDel字段
	 *
	 * @param groupID
	 * @return
	 */
	public int doDeleteGroup(Long groupID) {
		logger.debug("doDeleteGroup:groupID:" + groupID);

		int effectRowCount = 0;
		CmsgGroup cmsgGroup = new CmsgGroup();
		cmsgGroup.setGroupId(groupID);
		cmsgGroup.setIsDel("1");
		effectRowCount = genericDao.update(cmsgGroup, new String[]{"isDel"});
		return effectRowCount;
	}

	/**
	 * 根据用户id和组名称，创建一个新组，并返回新建的组的对象
	 *
	 * @param userId
	 * @param groupName
	 * @return 新建的组的对象
	 */
	public CmsgGroup doCreateGroup(String userId, String groupName) {
		logger.debug("doCreateGroup:userId:" + userId + ",groupName:" + groupName);

		if (groupName == null || userId == null) {
			logger.error("[ERRORINFO]doCreateGroup:userId、groupName不能为空");
			return null;
		}
		CmsgGroup cmsgGroup = new CmsgGroup();
		Long groupPk;

		cmsgGroup.setGroupId(null);
		cmsgGroup.setGroupName(groupName);
		cmsgGroup.setCreateUserId(userId);
		cmsgGroup.setIsDel("0");
		cmsgGroup.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
		groupPk = genericDao.insert(cmsgGroup);
		cmsgGroup.setGroupId(groupPk);

		return cmsgGroup;
	}

	/**
	 * 根据用户ID 获取该用户的组列表 然后返回 easyui datagrid table所用的格式
	 *
	 * @param userId
	 * @return easyui datagrid table所用的格式
	 */
	public HashMap getMyGroupTableData(String userId) {
		logger.debug("getMyGroupTableData: userId:" + userId);

		List<CmsgGroup> groupList = getMyGroupListByUserID(userId);
		HashMap result;
		List<HashMap> rows;
		if (groupList == null) {
			logger.error("[ERRORINFO]getMyGroupTableData: 未找到用户的组");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();

		for (CmsgGroup oneGroup : groupList) {
			if (oneGroup.getGroupId() != null && oneGroup.getGroupId() != 0) {
				HashMap row = new HashMap();
				row.put("groupID", oneGroup.getGroupId());
				row.put("groupName", oneGroup.getGroupName());
				rows.add(row);
			}
		}

		result.put("total", groupList.size());
		result.put("rows", rows);
		return result;
	}

	/**
	 * 根据用户ID 获取该用户的组的列表
	 *
	 * @param userId
	 * @return 用户组的列表
	 */
	public List<CmsgGroup> getMyGroupListByUserID(String userId) {
		logger.debug("getMyGroupListByUserID:userId:" + userId);

		if (userId == null) {
			logger.error("[ERRORINFO]getMyGroupListByUserID:userId不能为空");
			return null;
		}
		Condition condition = new Condition();
		condition.add("createUserId", userId);
		condition.add("isDel", "0");

		OrderPart orders = new OrderPart();
		orders.add("createTimestamp", OrderPart.ASC);
		List<CmsgGroup> result = genericDao.getByCondition(CmsgGroup.class, condition, orders);
		return result;
	}

	public List<CmsgGroup> getCmsgGroupByGroupIDList(List<CmsgGroup> groupIDList) {
		logger.debug("getCmsgGroupByGroupIDList:groupIDList:" + groupIDList);

		if (groupIDList == null) {
			logger.error("[ERRORINFO]getCmsgGroupByGroupIDList:传入的List 为null");
			return null;
		} else if (groupIDList.size() < 0) {
			logger.error("[ERRORINFO]getCmsgGroupByGroupIDList:传入的List 的size小于0");
			return null;
		}
		Condition condition = new Condition();
		for (CmsgGroup cmsgGroup : groupIDList) {
			if (cmsgGroup.getGroupId() != null && cmsgGroup.getGroupId() != 0) {
				condition.add("groupId", "=", cmsgGroup.getGroupId(), "or");
			}
		}

//		再检查一遍condition 看看有没有值
		if (condition.isEmpty()) {
			logger.error("[ERRORINFO]getCmsgGroupByGroupIDList:condition 为空");
			return null;
		}
		condition.add("isDel", "0");
		OrderPart orders = new OrderPart();
		orders.add("createTimestamp", OrderPart.ASC);

		List<CmsgGroup> result = genericDao.getByCondition(CmsgGroup.class, condition, orders);
		return result;
	}

	/**
	 * 根据groupID 获取群组子表
	 *
	 * @param groupID
	 * @return
	 */
	public List<CmsgGroupSub> getGpSubListByGpID(String groupID) {
		logger.debug("getGpSubListByGpID:groupID:" + groupID);

		if (groupID == null) {
			logger.error("[ERRORINFO]getGpSubListByGpID:groupID不能为空");
			return null;
		}
		Condition condition = new Condition();
		condition.add("groupId", groupID);

		List<CmsgGroupSub> result = genericDao.getByCondition(CmsgGroupSub.class, condition, null);
		return result;
	}

	/**
	 * 根据群组ID 获取该群组下的人员，并找到他们的姓名、电话、部门名称
	 *
	 * @param groupID
	 * @return
	 */
	public List<CmsgMember> getGpMemberListByGpID(String groupID) {
		logger.debug("getGpMemberListByGpID:groupID" + groupID);

		if (groupID == null) {
			logger.error("[ERRORINFO]getGpMemberListByGpID:groupID不能为空");
			return null;
		}
		HashMap conditionMap = new HashMap();
		conditionMap.put("groupId", groupID);

		List<CmsgMember> result = genericDao.queryBySqlID("platform.cmsggroupsub.CmsgMemberByGpID", conditionMap);
		return result;
	}

//	public List<CmsgMember> getGpMemberListByGpIDList(List<CmsgGroup> cmsgGroupList) {
//		logger.debug("getGpMemberListByGpIDList:cmsgGroupList" + cmsgGroupList);
//
//		if (cmsgGroupList == null) {
//			logger.debug("[ERRORINFO]getGpMemberListByGpIDList:传入的List 为null");
//			return null;
//		} else if (cmsgGroupList.size() < 0) {
//			logger.debug("[ERRORINFO]getGpMemberListByGpIDList:传入的List 的size小于0");
//			return null;
//		}
//		//转换conditionMap
//		HashMap conditionMap = new HashMap();
//		for (CmsgGroup cmsgGroup : cmsgGroupList) {
//			if (cmsgGroup.getGroupId() != null && cmsgGroup.getGroupId() != 0) {
//				conditionMap.put("groupId", cmsgGroup.getGroupId());
//			}
//		}
//		//再次检查conditionMap不为空
//		if (conditionMap.size() < 1) {
//			logger.debug("[ERRORINFO]getGpMemberListByGpID:conditionMap为空");
//			return null;
//		}
//		List<CmsgMember> result = genericDao.queryBySqlID("platform.cmsggroupsub.CmsgMemberByGpID", conditionMap);
//		return result;
//	}

	/**
	 * 查找groupList中的所有groupID，并按前台“待发送人员”的表格格式，返回组中的成员
	 *
	 * @param groupList
	 * @return
	 */
	public HashMap getRetrievePersonTDataByGroupIDList(List<CmsgGroup> groupList) {
		logger.debug("getRetrievePersonTDataByGroupIDList: groupList:" + groupList);

		HashMap result;
		List<HashMap> rows;

		if (groupList == null || groupList.size() < 1) {
			logger.error("[ERRORINFO]getRetrievePersonTDataByGroupIDList群组列表为空");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();

		for (CmsgGroup group : groupList) {
			if (group.getGroupId() == null || group.getGroupId() == 0) {
				logger.error("[ERRORINFO]getRetrievePersonTDataByGroupIDList当前群组ID为空");
				continue;
			}
			String groupName = group.getGroupName();
			Long groupID = group.getGroupId();

			List<CmsgMember> memberListByGpID = getGpMemberListByGpID(String.valueOf(groupID));
			if (memberListByGpID == null || memberListByGpID.size() < 0) {
				logger.error("[ERRORINFO]getRetrievePersonTDataByGroupIDList群组[" + groupName + "](" + groupID + ")下没有成员");
				continue;
			}
			for (CmsgMember member : memberListByGpID) {
				HashMap row = new HashMap();
				row.put("zPerno", member.getUserId());
				row.put("zPerna", member.getZPerna());
				row.put("zMobph", member.getZMobph());
				row.put("zGroupNm", groupName);
				row.put("zGroupNo", groupID);
				row.put("zDept", member.getZDept());
				rows.add(row);
			}
		}
		//没有就返回null
		if (rows.size() < 1) {
			return null;
		}
		result.put("total", rows.size());
		result.put("rows", rows);
		return result;
	}

	/**
	 * 根据用户id 获取该用户
	 * 在自定义群组、发送的自定义文本消息、发送的会议消息中 添加过的台外人员
	 *
	 * @param userId
	 * @return 返回  easyui datagrid table所用的格式
	 */
	public HashMap getAddedOutPersonTableData(String userId) {
		logger.debug("getAddedOutPersonTableData: userId:" + userId);

		List<AddedOutsidePerson> personList = getAddedOutsidePerson(userId);
		HashMap result;
		List<HashMap> rows;
		if (personList == null) {
			logger.error("[ERRORINFO]getGpMemberTableData: " + userId + "没有添加的台外人员");
			return null;
		}
		result = new HashMap();
		rows = new ArrayList<HashMap>();

		for (AddedOutsidePerson onePerson : personList) {
			HashMap row = new HashMap();
			row.put("zMobph", onePerson.getUserId());
			row.put("zPerna", onePerson.getZPerna());
			rows.add(row);
		}

		result.put("total", personList.size());
		result.put("rows", rows);
		return result;
	}

	/**
	 * 根据用户id 获取该用户
	 * 在自定义群组、发送的自定义文本消息、发送的会议消息中 添加过的台外人员
	 *
	 * @param userId
	 * @return
	 */
	public List<AddedOutsidePerson> getAddedOutsidePerson(String userId) {
		logger.debug("getAddedOutsidePerson:userId:" + userId);
		if (StringUtils.isEmpty(userId)) {
			logger.debug("getAddedOutsidePerson: userId不能为空");
			return null;
		}
		HashMap conditionMap = new HashMap();
		conditionMap.put("userId", userId);

		return genericDao.queryBySqlID("platform.customMessage.AddedOutsidePerson", conditionMap);
	}

	/**
	 * 根据：
	 * 工号精确查找
	 * 用户姓名、用户部门名称 模糊查找
	 *
	 * @param personNo
	 * @param personName
	 * @param deptName
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public List<PersonWithDept> getStaffList(String personNo, String personName, String deptName, int pageNo, int pageSize) {
		logger.debug("getStaffList:personNo:" + personNo + ",personName:" + personName + ",deptName:" + deptName
				+ ",pageNo:" + pageNo + ",pageSize:" + pageSize);

		Map map = new HashMap();
		if (StringUtils.isNotEmpty(personNo)) {        //有员工工号 就只查员工工号
			map.put("zPerno", personNo);
		} else {
			if (StringUtils.isNotEmpty(personName)) {
				map.put("zPerna", personName);
			}
			if (StringUtils.isNotEmpty(deptName)) {
				map.put("zDeptNm", deptName);
			}
		}

		map.put("zType", 0);
//		map.put("orderNamePinyin", "ASC");
		map.put("orderPerno", "ASC");
		if (pageSize <= 0) {
			return genericDao.queryBySqlID("platform.person.PersonWithDept", map);
		} else {
			return genericDao.queryBySqlIDPage("platform.person.PersonWithDept", map, pageNo, pageSize);
		}
	}

	/**
	 * 根据用户ID，获取该用户信息
	 *
	 * @param zPerno
	 * @return
	 */

	public Person getPersonInfo(String zPerno) {
		logger.debug("getPersonInfo:zPerno:" + zPerno);

		Condition condition = new Condition();
		condition.add("zPerno", zPerno);
		List<Person> result = genericDao.getByCondition(Person.class, condition, null);
		if (result.size() > 0) {
			return result.get(0);
		} else {
			logger.debug("getPersonInfo:未找到对应条目");
			return null;
		}
	}

	/**
	 * 根据用户ID 查找该用户的部门代码
	 *
	 * @param userID
	 * @return
	 */
	public String getDeptIDByUserId(String userID) {
		logger.debug("getDeptIDByUserId: userID:" + userID);

		if (userID == null) {
			return null;
		}

		Person person = getPersonInfo(userID);
		if (person != null) {
			String str_dept;
			if (StringUtils.isNotEmpty(person.getZDept())) {
				str_dept = person.getZDept();
			} else if (StringUtils.isNotEmpty(person.getZSector())) {
				str_dept = person.getZSector();
			} else {
				str_dept = person.getZCentre();
			}
			return str_dept;
		} else {
			return null;
		}
	}

	/**
	 * 检查自定义会议通知是否在库中
	 *
	 * @param pk
	 * @return
	 */
	public boolean checkCmsgMeetingIsExist(Long pk) {
		logger.debug("checkCmsgMeetingIsExist: pk(long):" + pk);

		if (pk == null) {
			logger.debug("checkCmsgMeetingIsExist: pk is Null");
			return false;
		}
		List<Map<String, ?>> result;
		StringBuffer sql = new StringBuffer("select 1 from t_cmsg_meeting ");
		sql.append(" where f_message_pk=").append(pk.toString()).append(" limit 1 ");
		result = genericDao.executeSql(sql.toString());
		if (result.isEmpty()) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 检查自定义会议通知是否在库中
	 *
	 * @param str_pk
	 * @return
	 */
	public boolean checkCmsgMeetingIsExist(String str_pk) {
		logger.debug("checkCmsgMeetingIsExist: pk(string):" + str_pk);

		Long L_pk;
		try {
			L_pk = Long.valueOf(str_pk);
		} catch (NumberFormatException e) {
			return false;
		}
		return checkCmsgMeetingIsExist(L_pk);
	}
}
